﻿using KTD.Web.BLL;
using KTD.Web.Models;
using KTD.Web.Models.VD;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using XXS.Common;
using XXS.Common.ControllerExt;

namespace KTD.Web.Controllers
{
    public class ImportController : Controller
    {
        // GET: Import
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DeyangList()
        {

            try
            {
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(3575, "什邡");
                dic.Add(3576 , "绵竹");
                dic.Add(3577 , "罗江");
                dic.Add(3579 , "德阳周边");
                dic.Add(3580 , "广汉市");
                dic.Add(4360 , "老城区");
                dic.Add(4361 , "城北片区");
                dic.Add(4362 , "旌东片区");
                dic.Add(4363 , "旌南片区");
                dic.Add(4364, "黄河片区");
                dic.Add(4365  , "经开区");
                dic.Add(4366 , "天元片区");
                dic.Add(4367 , "孝泉镇");
                dic.Add(4368 , "高铁新区");
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
                for (int i = 1; i <= 20; i++)
                {
                   
                    var listStr = new WebClient()
                    {
                        Encoding = Encoding.UTF8
                    }.DownloadString($"https://www.e0838.com/mobile/api/get_house_list?page={i}&limit=20&area=&shi=&mj=&jj=&sale_status=&wylx=");

                    JObject listObj = (JObject)JsonConvert.DeserializeObject<object>(listStr);
                    var idList = listObj["data"]["data"].ToList().Select(n =>n["id"]);


                    // JObject data = JsonConvert.DeserializeObject<JObject>(res);
                    foreach (var id in idList)
                    {
                        //var detailStr = new WebClient()
                        //{
                        //    //Encoding = Encoding.UTF8
                        //}.DownloadString($"https://www.e0838.com/mobile/api/get_house_info?aid={id}");

                        var detailStr = HttpPost("https://www.e0838.com/mobile/api/get_house_info", "aid=" + id);
                        JObject deteailObj = (JObject)JsonConvert.DeserializeObject<object>(detailStr);
                        if (deteailObj["msg"].ToString() == "success")
                        {
                            var data = deteailObj["data"];
                            HouseCUD cd = new HouseCUD();
                            cd.area = data["covered_area"].ToString();
                            cd.click =Convert.ToInt32(data["clicks"].ToString());
                            cd.clickstr = data["clicks"].ToString();
                            cd.special= data["comments"].ToString();
                            cd.staytime = data["completed_time"].ToString();
                            cd.decorate = data["decoration_situation"].ToString();
                            cd.companyname = data["developer"].ToString();
                            cd.cenghubi = data["elevator_situation"].ToString();
                            cd.housegreenrate = data["green_rate"].ToString();
                            cd.houseprice = (float)data["average_price"];
                            cd.price = data["average_price"].ToString();
                            cd.zongjia = data["min_zongjia"].ToString();
                            cd.wuyefei= data["property_cost"].ToString();
                            cd.opensaletime = data["property_name"].ToString();
                            cd.year = data["property_year"].ToString();
                            cd.housetype =string.Join("," ,data["property_type"].ToList().Select(n=>n.ToString()));//seo_keywords=商住,刚需
                            cd.tel = data["sale_tel"].ToString();
                            cd.housename = data["subject"].ToString();
                            cd.houseaddress = data["subject_address"].ToString();
                            cd.lng = Convert.ToSingle(data["subject_coordinates"].ToString().Split(',')[0]);
                            cd.lat = Convert.ToSingle(data["subject_coordinates"].ToString().Split(',')[1]);
                            cd.content = data["subject_describe"].ToString();
                            cd.tongqi= data["supply_gas_mode"].ToString();
                            cd.rongJiLv = data["volume_rate"].ToString();
                            cd.cheWeiBi = data["parking_situation"].ToString();
                            cd.zonghushu = data["plan_household"].ToString(); 
                            cd.housearea = data["mj_fw"].ToString();
                            cd.thumb = data["thumb"].ToString();
                            cd.uid =Convert.ToInt32( data["id"].ToString());
                            var imgName1 = "/Attachment/deyang/" + Guid.NewGuid().ToString() + ".jpg";
                           
                            Down(cd.thumb, imgName1);
                            cd.thumb = imgName1;
                            try {
                                var areaname = dic[Convert.ToInt32(data["area"].ToString())];
                                cd.areaname = areaname;
                            }
                            catch(Exception ex){
                                cd.areaname = "德阳周边";
                            }
                           
                            cd.channel = "new";
                            var img_list = data["view"]["pic"].ToList();
                            cd.thumb_urls = new List<string>();
                            cd.thumb_1s = new List<string>();
                            cd.thumb_2s = new List<string>();
                            cd.thumb_3s = new List<string>();
                            foreach (var img in img_list) {
                                
                                var url = img["pic"].ToString();
                                var type = img["type"].ToString();
                                if (type != "0")
                                {
                                    var imgName = "/Attachment/deyang/" + Guid.NewGuid().ToString() + ".jpg";
                                    Down(url, imgName);
                                    //效果图
                                    if (type == "1")
                                    {
                                        cd.thumb_urls.Add(imgName);
                                    }
                                    //else if (type == "2")//
                                    //{ 
                                    
                                    //}
                                    else if (type == "3")
                                    {
                                        cd.thumb_2s.Add( imgName );
                                       // cd.thumb_2s.Add(url);
                                    }
                                    else if (type == "4")
                                    {
                                        cd.thumb_3s.Add(imgName);
                                        //cd.thumb_3s.Add(url);
                                    }
                                }
                                
                            }
                            cd.thumb_url = cd.thumb_urls.ToJoinWith(",");
                            cd.thumb_1 = cd.thumb_1s.ToJoinWith(",");
                            cd.thumb_2 = cd.thumb_2s.ToJoinWith(",");
                            cd.thumb_3 = cd.thumb_3s.ToJoinWith(",");
                            var houseId= MF.HouseManager.Create(cd);
                            if (houseId != 0)
                            {
                                var zygw_list = data["zygw_list"].ToList();
                                foreach (var zygw in zygw_list)
                                {
                                    SalerCD saler = new SalerCD();
                                    saler.houseid = houseId;
                                    saler.housename = cd.housename;
                                    saler.avatar = zygw["avatar"].ToString();
                                    saler.tel = zygw["mobile"].ToString();
                                    saler.name = zygw["nickname"].ToString();
                                    saler.wechat = zygw["wx_number"].ToString();
                                    saler.code = zygw["wx_number"].ToString();

                                    MF.SalerManager.Create(saler);
                                }
                            }
                            
                           

                        }
                       
                        
                    }
                }



                return this.JsonNet(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.JsonNet(new { success = false, msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }



        public ActionResult MianyangList()
        {

            try
            {
              
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
                for (int i = 1; i <= 15; i++)
                {

                    var listStr = new WebClient()
                    {
                        Encoding = Encoding.UTF8
                    }.DownloadString($"https://p.hangjiayun.com/to/xishu365/house/api/housewapapi/plist?page={i}&is_mini=1 ");

                    JObject listObj = (JObject)JsonConvert.DeserializeObject<object>(listStr);
                    var list = listObj["data"]["list"].ToList();
                    

                    // JObject data = JsonConvert.DeserializeObject<JObject>(res);
                    foreach (var item in list)
                    {
                        var id = item["id"].ToString();
                        var areaname = item["area"].ToString();
                        if (areaname == "高新区" || areaname == "科创园区" || areaname == "经开区")
                        {
                            areaname = "绵阳" + areaname;
                        }

                        var detailStr = new WebClient()
                        {
                            Encoding = Encoding.UTF8
                        }.DownloadString($"https://p.hangjiayun.com/to/xishu365/house/api/housewapapi/pdetail?hid={id}&is_mini=1 ");


                        JObject deteailObj = (JObject)JsonConvert.DeserializeObject<object>(detailStr);
                        if (deteailObj["status"].ToString() == "success")
                        {
                            var data = deteailObj["data"];
                            HouseCUD cd = new HouseCUD();
                            cd.uid = Convert.ToInt32(item["id"].ToString());
                            cd.lat =Convert.ToSingle(item["map_lat"].ToString());
                            cd.lng = Convert.ToSingle(item["map_lng"].ToString());
                            cd.price = item["price"].ToString();
                            if (!string.IsNullOrEmpty(cd.price))
                            {
                                cd.houseprice = Convert.ToSingle(item["price"].ToString().Replace("元/㎡", ""));
                            }
                            
                            //cd.staytime= item["openTime"].ToString();
                            cd.houseaddress = data["address"].ToString();
                            cd.rongJiLv = data["capactiy"].ToString();
                            cd.cheWeiBi = data["carport"].ToString();
                            cd.content = data["content"].ToString();
                            cd.companyname = data["developer"].ToString();
                            cd.cenghubi = data["floor_desc"].ToString();
                            cd.housegreenrate = data["green"].ToString();
                            cd.zonghushu = data["household_num"].ToString();
                            cd.opensaletime = data["manage_company"].ToString();
                            cd.wuyefei = data["manage_fee"].ToString();
                            cd.housename = data["plot_name"].ToString();
                            cd.year = data["property_years"].ToString();
                            cd.tel = data["sale_tel"].ToString();
                            cd.housetype = string.Join(",", data["wylx"].ToList().Select(n => n.ToString()));
                            cd.decorate = string.Join(",", data["zxzt"].ToList().Select(n => n.ToString()));
                            
                            cd.thumb = item["image"].ToString();
                            cd.thumb_url= item["image"].ToString();


                            var imgName1 = "/Attachment/mianyang/" + Guid.NewGuid().ToString() + ".jpg";
                            Down(cd.thumb, imgName1);
                            cd.thumb =  imgName1;

                            cd.areaname = areaname;
                            cd.channel = "new";
                            



                            var imgStr = new WebClient()
                            {
                                Encoding = Encoding.UTF8
                            }.DownloadString($"https://p.hangjiayun.com/to/xishu365/house/api/housewapapi/palbum?hid={id}&is_mini=1 ");
                            JObject imgObj = (JObject)JsonConvert.DeserializeObject<object>(imgStr);
                            var img_list = imgObj["data"]["images"].ToList();
                            cd.thumb_urls = new List<string>();
                            cd.thumb_1s = new List<string>();
                            cd.thumb_2s = new List<string>();
                            cd.thumb_3s = new List<string>();
                            foreach (var img in img_list)
                            {

                                var imgs = img["data"].ToList();
                                var type = img["name"].ToString();
                              
                                
                                //效果图
                                if (type == "效果图"|| type == "实景图")
                                {
                                    foreach (var image in imgs)
                                    {
                                        var imgName = "/Attachment/mianyang/" + Guid.NewGuid().ToString() + ".jpg";
                                        var url = image["url"].ToString();
                                        Down(url, imgName);
                                        cd.thumb_urls.Add(imgName);
                                    }
                                   
                                }
                                else if (type == "样板间")//
                                {
                                    foreach (var image in imgs)
                                    {
                                        var imgName = "/Attachment/mianyang/" + Guid.NewGuid().ToString() + ".jpg";
                                        var url = image["url"].ToString();
                                        Down(url, imgName);
                                        cd.thumb_2s.Add(imgName);
                                    }
                                }
                                else if (type == "配套图"|| type == "交通图")
                                {
                                    foreach (var image in imgs)
                                    {
                                        var imgName = "/Attachment/mianyang/" + Guid.NewGuid().ToString() + ".jpg";
                                        var url = image["url"].ToString();
                                        Down(url, imgName);
                                        cd.thumb_3s.Add(imgName);
                                    }
                                }
                              
                                

                            }
                            var huxingStr = new WebClient()
                            {
                                Encoding = Encoding.UTF8
                            }.DownloadString($"https://p.hangjiayun.com/to/xishu365/house/api/housewapapi/pindex?id={id}&is_mini=1");


                            JObject huxingObj = (JObject)JsonConvert.DeserializeObject<object>(huxingStr);
                        
                            if (huxingObj["data"]["houseTypes"] != null&& huxingObj["data"]["houseTypes"].Count()!=0&& huxingObj["data"]["houseTypes"]["demo"]!=null)
                            {
                                var huxings = huxingObj["data"]["houseTypes"]["demo"].ToList();

                                foreach (var huxing in huxings)
                                {
                                    var imgName = "/Attachment/mianyang/" + Guid.NewGuid().ToString() + ".jpg";
                                    var url = huxing["image"].ToString();
                                    Down(url, imgName);
                                    cd.thumb_1s.Add(imgName);
                                }
                            }
                            
                            cd.thumb_url = cd.thumb_urls.ToJoinWith(",");
                            cd.thumb_1 = cd.thumb_1s.ToJoinWith(",");
                            cd.thumb_2 = cd.thumb_2s.ToJoinWith(",");
                            cd.thumb_3 = cd.thumb_3s.ToJoinWith(",");
                            var houseId = MF.HouseManager.Create(cd);
                          
                        }


                    }
                }



                return this.JsonNet(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return this.JsonNet(new { success = false, msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }




        private string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            request.Host = "www.e0838.com";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36";
            //request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// 执行下载并保存到本地
        /// </summary>
        /// <param name="url">图片地址</param>
        /// <param name="dtnow">保存的文件名</param>

        public void Down(string url, string dtnow)
        {
            try
            {
                WebRequest wreq = WebRequest.Create(url);

                HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
                Stream s = wresp.GetResponseStream();
                System.Drawing.Image img;
                img = System.Drawing.Image.FromStream(s);
                img.Save(Server.MapPath(dtnow), ImageFormat.Jpeg);
                MemoryStream ms = new MemoryStream();
                img.Save(ms, ImageFormat.Jpeg);
                img.Dispose();
            }
            catch
            { 
                
            }


        }
    }
}